package com.yjps.system.service;

import com.yjps.common.page.Pager;
import com.yjps.system.dao.OrderDao;
import com.yjps.system.model.Order;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by jessy on 2015/8/25.
 */
@Service
public class OrderService {
    Logger log = LoggerFactory.getLogger(OrderService.class);
    @Autowired
    OrderDao orderDao;
    public int save(Order order){
        return orderDao.save(order);
    }

    public Order getOrder(int id){
        return orderDao.load(id);
    }

    public void updateOrder(Order order){
        String hql = "update Order o set o.orderTime =:orderTime,o.orderState =:orderState,o.acceptTime =:acceptTime,o.acceptResult =:acceptResult" +
                " where o.id =:id";
        Map<String, Object> map = new HashMap<>();
        map.put("orderTime",order.getOrderTime());
        map.put("orderState",order.getOrderState());
        map.put("acceptTime",order.getAcceptTime());
        map.put("acceptResult",order.getAcceptResult());
        map.put("id",order.getId());
        orderDao.excute(hql, map);
    }

    /**
     * 获取指定门店经理的订单
     * @param pager
     * @param agentId
     * @return
     * @throws Exception
     */
    public Pager<Order> getOrderByPager(Pager<Order> pager,int agentId,String acceptResult) throws Exception {
        Map<String, Object> params = new HashMap<>();
        String queryString = "from Order t where t.isValid = 1 and t.agentId =:agentId";
        if(!StringUtils.isEmpty(acceptResult)) {
            queryString += " and t.acceptResult =:acceptResult";
            params.put("acceptResult", Integer.parseInt(acceptResult));
        }
        queryString += " order by t.id desc";
        params.put("agentId",agentId);
        List<Order> accounts = orderDao.findWithSelect(queryString, params, (pager.getPageNo()-1)*pager.getPageSize(), pager.getPageSize());
        pager.setCount(orderDao.getTotalCount(queryString, params));
        pager.setList(accounts);
        return pager;
    }

    public void delete(int id){
        orderDao.invalid(getOrder(id));
    }
}
